<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第六章：块与大中枢派发(2)第41条：多用派发队列，少用同步锁如果有多个线程要执行同一份代码，那么有时可能会出问题。这种情况下，通常要使用锁来实现同步机制。在GCD出现之前，一般有两种方式可以实现同步   原始方法：synchronized &amp; NSLock12345- (void)synchronizedMethod &amp;#123;    @synchronized (self) &amp;#12">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第六章阅读笔记(2)">
<meta property="og:url" content="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第六章：块与大中枢派发(2)第41条：多用派发队列，少用同步锁如果有多个线程要执行同一份代码，那么有时可能会出问题。这种情况下，通常要使用锁来实现同步机制。在GCD出现之前，一般有两种方式可以实现同步   原始方法：synchronized &amp; NSLock12345- (void)synchronizedMethod &amp;#123;    @synchronized (self) &amp;#12">
<meta property="og:locale">
<meta property="og:image" content="http://ovsbvt5li.bkt.clouddn.com/18-5-24/62516339.jpg">
<meta property="article:published_time" content="2018-05-22T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:20:40.179Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ovsbvt5li.bkt.clouddn.com/18-5-24/62516339.jpg">


<link rel="canonical" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/","path":"2018/05/2018/05/《Effective Objective-C 2.0》第六章阅读笔记(2)/","title":"《Effective Objective-C 2.0》第六章阅读笔记(2)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第六章阅读笔记(2) | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E5%85%AD%E7%AB%A0%EF%BC%9A%E5%9D%97%E4%B8%8E%E5%A4%A7%E4%B8%AD%E6%9E%A2%E6%B4%BE%E5%8F%91-2"><span class="nav-number">1.</span> <span class="nav-text">第六章：块与大中枢派发(2)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC41%E6%9D%A1%EF%BC%9A%E5%A4%9A%E7%94%A8%E6%B4%BE%E5%8F%91%E9%98%9F%E5%88%97%EF%BC%8C%E5%B0%91%E7%94%A8%E5%90%8C%E6%AD%A5%E9%94%81"><span class="nav-number">1.1.</span> <span class="nav-text">第41条：多用派发队列，少用同步锁</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8E%9F%E5%A7%8B%E6%96%B9%E6%B3%95%EF%BC%9Asynchronized-amp-NSLock"><span class="nav-number">1.1.1.</span> <span class="nav-text">原始方法：synchronized &amp; NSLock</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%94%B9%E8%BF%9B%E6%96%B9%E6%B3%95%EF%BC%9A%E4%B8%B2%E8%A1%8C%E5%90%8C%E6%AD%A5%E9%98%9F%E5%88%97"><span class="nav-number">1.1.2.</span> <span class="nav-text">改进方法：串行同步队列</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%80%E4%BC%98%E6%96%B9%E6%A1%88%EF%BC%9Adispatch-barrier"><span class="nav-number">1.1.3.</span> <span class="nav-text">最优方案：dispatch_barrier</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.1.4.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC42%E6%9D%A1%EF%BC%9A%E5%A4%9A%E7%94%A8-GCD%EF%BC%8C%E5%B0%91%E7%94%A8-performSelector-%E7%B3%BB%E5%88%97%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">第42条：多用 GCD，少用 performSelector 系列方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8F%AF%E8%83%BD%E4%BC%9A%E5%BC%95%E8%B5%B7%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">可能会引起内存泄漏</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC%E5%8F%AA%E8%83%BD%E6%98%AF-void-%E6%88%96%E5%AF%B9%E8%B1%A1%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">返回值只能是 void 或对象类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%A0%E5%85%A5%E5%8F%82%E6%95%B0%E6%9C%89%E9%99%90%E5%88%B6"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">传入参数有限制</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%94%B9%E8%BF%9B%EF%BC%88GCD%EF%BC%89"><span class="nav-number">1.2.1.</span> <span class="nav-text">改进（GCD）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC43%E6%9D%A1%EF%BC%9A%E6%8E%8C%E6%8F%A1-GCD-%E5%8F%8A-NSOperationQueue-%E7%9A%84%E4%BD%BF%E7%94%A8%E6%97%B6%E6%9C%BA"><span class="nav-number">1.3.</span> <span class="nav-text">第43条：掌握 GCD 及 NSOperationQueue 的使用时机</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-NSOperationQueue-%E4%BC%98%E7%82%B9"><span class="nav-number">1.3.1.</span> <span class="nav-text">使用 NSOperationQueue 优点</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8F%96%E6%B6%88%E6%9F%90%E4%B8%AA%E6%93%8D%E4%BD%9C"><span class="nav-number">1.3.1.1.</span> <span class="nav-text">取消某个操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%8C%87%E5%AE%9A%E6%93%8D%E4%BD%9C%E9%97%B4%E7%9A%84%E4%BE%9D%E8%B5%96%E5%85%B3%E7%B3%BB"><span class="nav-number">1.3.1.2.</span> <span class="nav-text">指定操作间的依赖关系</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%80%9A%E8%BF%87%E9%94%AE%E5%80%BC%E8%A7%82%E6%B5%8B%E6%9C%BA%E5%88%B6%E7%9B%91%E6%8E%A7-NSOperation-%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="nav-number">1.3.1.3.</span> <span class="nav-text">通过键值观测机制监控 NSOperation 对象的属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%8C%87%E5%AE%9A%E6%93%8D%E4%BD%9C%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-number">1.3.1.4.</span> <span class="nav-text">指定操作的优先级</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%87%8D%E7%94%A8-NSOperation-%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.3.1.5.</span> <span class="nav-text">重用 NSOperation 对象</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93-1"><span class="nav-number">1.3.2.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第六章阅读笔记(2) | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第六章阅读笔记(2)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-05-23 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-23T00:00:00+08:00">2018-05-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:20:40" itemprop="dateModified" datetime="2018-07-01T16:20:40+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第六章：块与大中枢派发-2"><a href="#第六章：块与大中枢派发-2" class="headerlink" title="第六章：块与大中枢派发(2)"></a><center>第六章：块与大中枢派发(2)</center></h1><h2 id="第41条：多用派发队列，少用同步锁"><a href="#第41条：多用派发队列，少用同步锁" class="headerlink" title="第41条：多用派发队列，少用同步锁"></a>第41条：多用派发队列，少用同步锁</h2><p>如果有多个线程要执行同一份代码，那么有时可能会出问题。这种情况下，通常要使用锁来实现同步机制。在GCD出现之前，一般有两种方式可以实现同步  </p>
<h3 id="原始方法：synchronized-amp-NSLock"><a href="#原始方法：synchronized-amp-NSLock" class="headerlink" title="原始方法：synchronized &amp; NSLock"></a>原始方法：synchronized &amp; NSLock</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)synchronizedMethod &#123;</span><br><span class="line">    <span class="keyword">@synchronized</span> (<span class="keyword">self</span>) &#123;</span><br><span class="line">        <span class="comment">// Safe</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">_lock = [[<span class="built_in">NSLock</span> alloc] init];</span><br><span class="line">- (<span class="type">void</span>)synchronizedMethod &#123;</span><br><span class="line">    [_lock lock];</span><br><span class="line">    <span class="comment">// Safe</span></span><br><span class="line">    [_lock unlock];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>滥用 @synchronized(self) 会很危险，因为所有同步块都会彼此抢夺同一个锁。要是有很多个属性都这么写的话，那么每个属性的同步块都要等其他所有同步块执行完毕才能执行。两种方法的使用效率都不高，并且处理不当会造成死锁。</p>
<h3 id="改进方法：串行同步队列"><a href="#改进方法：串行同步队列" class="headerlink" title="改进方法：串行同步队列"></a>改进方法：串行同步队列</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">_syncQueue = dispatch_queue_create(<span class="string">&quot;com.vhuichen.syncQueue&quot;</span>, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line">- (<span class="built_in">NSString</span> *)someString &#123; </span><br><span class="line">	__block <span class="built_in">NSString</span> *localSomeString; </span><br><span class="line">	<span class="built_in">dispatch_sync</span>(_syncQueue, ^&#123; </span><br><span class="line">		localSomeString = _someString; </span><br><span class="line">	&#125;);</span><br><span class="line">	<span class="keyword">return</span> localSomeString;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)setSomeString:(<span class="built_in">NSString</span> *)someString &#123; </span><br><span class="line">	<span class="built_in">dispatch_sync</span>(_syncQueue, ^&#123; </span><br><span class="line">		_someString = someString; </span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有一种方案就是可以把 setter 方法改成异步执行，提升程序的执行速度。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)setSomeString:(<span class="built_in">NSString</span> *)someString &#123; </span><br><span class="line">	<span class="built_in">dispatch_async</span>(_syncQueue, ^&#123; </span><br><span class="line">		_someString = someString; </span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里需要考虑的是：执行异步派发时，需要拷贝块。若拷贝块所需的时间明显超过执行块所花的时间，那么这种做法将比原来的更慢。只有当拷贝块所花的时间远低于执行块所花的时间时，可以考虑这种异步方法。</p>
<h3 id="最优方案：dispatch-barrier"><a href="#最优方案：dispatch-barrier" class="headerlink" title="最优方案：dispatch_barrier"></a>最优方案：dispatch_barrier</h3><p>事实上，获取值时可以多个同时进行，设置值和获取值不能同时进行。利用这个特点，我们可以对代码再次优化。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">_syncQueue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="literal">NULL</span>); </span><br><span class="line"></span><br><span class="line">- (<span class="built_in">NSString</span> *)someString &#123;</span><br><span class="line">	__block <span class="built_in">NSString</span> *localSomeString;</span><br><span class="line">	<span class="built_in">dispatch_sync</span>(_syncQueue, ^&#123;</span><br><span class="line">		localSomeString = _someString;</span><br><span class="line">	&#125;);</span><br><span class="line">	<span class="keyword">return</span> localSomeString;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)setSomeString:(<span class="built_in">NSString</span> *)someString &#123;</span><br><span class="line">	<span class="comment">// 这是使用 async 还是 sync 取决于 block 的业务逻辑复杂度，上面有解释</span></span><br><span class="line">	dispatch_barrier_async(_syncQueue, ^&#123;</span><br><span class="line">		_someString = someString;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的代码，我们创建的是一个并行队列。读取操作可以并行，但写入操作是单独执行的，因为给它加了栅栏，代码的执行逻辑如下图<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-5-24/62516339.jpg">  </p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>使用GCD实现同步方式，比使用 synchronized 或 NSLock 更高效。</p>
<h2 id="第42条：多用-GCD，少用-performSelector-系列方法"><a href="#第42条：多用-GCD，少用-performSelector-系列方法" class="headerlink" title="第42条：多用 GCD，少用 performSelector 系列方法"></a>第42条：多用 GCD，少用 performSelector 系列方法</h2><p>performSelector 有几个缺点。</p>
<h4 id="可能会引起内存泄漏"><a href="#可能会引起内存泄漏" class="headerlink" title="可能会引起内存泄漏"></a>可能会引起内存泄漏</h4><p>看下面一段代码</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">SEL selector;</span><br><span class="line"><span class="keyword">if</span> (<span class="comment">/* ... */</span>) &#123;</span><br><span class="line">	selector = <span class="keyword">@selector</span>(newObject);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="comment">/* ... */</span>) &#123;</span><br><span class="line">	selector = <span class="keyword">@selector</span>(<span class="keyword">copy</span>); </span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	selector = <span class="keyword">@selector</span>(someProperty);</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">id</span> ret = [object performSelector:selector];</span><br></pre></td></tr></table></figure>
<p>编译器会发出如下警示信息  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">warning:PerformSelector may cause a leak because its selector is unknown</span><br></pre></td></tr></table></figure>
<p>原因在于，编译器并不知道将要调用的选择子的方法签名及返回值。由于编译器不知道方法名，所以就没办法运用 ARC 的内存管理规则来判定返回值是不是应该释放。鉴于此，ARC采用了比较谨慎的做法，就是不添加释放操作。然而这么做可能导致内存泄漏，因为方法在返回对象时可能已经将其保留了。</p>
<h4 id="返回值只能是-void-或对象类型"><a href="#返回值只能是-void-或对象类型" class="headerlink" title="返回值只能是 void 或对象类型"></a>返回值只能是 void 或对象类型</h4><p>如果想返回整数或浮点数等类型的值，那么就需要执行一些复杂的转换操作。如果返回的是结构体，则不能使用 performSelector 。</p>
<h4 id="传入参数有限制"><a href="#传入参数有限制" class="headerlink" title="传入参数有限制"></a>传入参数有限制</h4><p>传入参数必须为对象类型，最多只有两个限制。</p>
<h3 id="改进（GCD）"><a href="#改进（GCD）" class="headerlink" title="改进（GCD）"></a>改进（GCD）</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="keyword">self</span> performSelectorOnMainThread:<span class="keyword">@selector</span>(aSelector) withObject:<span class="literal">nil</span> waitUntilDone:<span class="literal">NO</span>];</span><br></pre></td></tr></table></figure>
<p>上面的功能可以通过 GCD 来实现 </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_async</span>(dispatch_get_main_queue(), ^&#123;</span><br><span class="line">	[<span class="keyword">self</span> aSelector];</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>其它 performSelector 的方法也一样可以用 GCD 的方法代替。</p>
<h2 id="第43条：掌握-GCD-及-NSOperationQueue-的使用时机"><a href="#第43条：掌握-GCD-及-NSOperationQueue-的使用时机" class="headerlink" title="第43条：掌握 GCD 及 NSOperationQueue 的使用时机"></a>第43条：掌握 GCD 及 NSOperationQueue 的使用时机</h2><h3 id="使用-NSOperationQueue-优点"><a href="#使用-NSOperationQueue-优点" class="headerlink" title="使用 NSOperationQueue 优点"></a>使用 NSOperationQueue 优点</h3><h4 id="取消某个操作"><a href="#取消某个操作" class="headerlink" title="取消某个操作"></a>取消某个操作</h4><p>使用 NSOperationQueue ，想要取消操作队列是很容易的。运行任务之前，可以在 NSOperation 对象上调用 cancel 方法，该方法会设置对象内的标志位，用以表明此任务不需执行，不过，已经启动的任务无法取消。GCD 则无法直接取消。</p>
<h4 id="指定操作间的依赖关系"><a href="#指定操作间的依赖关系" class="headerlink" title="指定操作间的依赖关系"></a>指定操作间的依赖关系</h4><p>一个操作可以依赖其他多个操作。开发者能够制定操作之间的依赖体系，使特定的操作必须在另外一个操作顺利执行完毕后方可执行。</p>
<h4 id="通过键值观测机制监控-NSOperation-对象的属性"><a href="#通过键值观测机制监控-NSOperation-对象的属性" class="headerlink" title="通过键值观测机制监控 NSOperation 对象的属性"></a>通过键值观测机制监控 NSOperation 对象的属性</h4><p>NSOperation 对象有许多属性都适合通过键值观测机制（KVO）来监听。比如可以通过 isCancelled 属性来判断任务是否已取消，又比如可以通过 isFinished 属性来判断任务是否已完成。</p>
<h4 id="指定操作的优先级"><a href="#指定操作的优先级" class="headerlink" title="指定操作的优先级"></a>指定操作的优先级</h4><p>操作的优先级表示此操作与队列中其他操作之间的优先级关系。优先级高的操作先执行，优先级低的后执行。</p>
<h4 id="重用-NSOperation-对象"><a href="#重用-NSOperation-对象" class="headerlink" title="重用 NSOperation 对象"></a>重用 NSOperation 对象</h4><p>系统内置了一些 NSOperation 的子类（比如 NSBlockOperation）以供开发者调用，要是不想用这些子类，可以自己创建。这些类就是普通的 Objective-C 对象，能够存放任何信息。对象在执行时可以充分利用存于其中的信息，而且还可以随意调用定义在类中的方法。NSOperation 类符合软件开发中的“不重复”（Don’t Repeat Yourself，DRY）原则。</p>
<h3 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h3><p>GCD 操作简单，NSOperation 则功能更多。熟练掌握两种方式，在各种各样的场景中运用自如。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%20URL%20Schemes/" rel="prev" title="iOS开发之 URL Schemes">
                  <i class="fa fa-chevron-left"></i> iOS开发之 URL Schemes
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/" rel="next" title="《Effective Objective-C 2.0》第六章阅读笔记(3)">
                  《Effective Objective-C 2.0》第六章阅读笔记(3) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
